<template>
  <div class="form-sparepart">
    <div class="btn-group">
      <!-- start 从物料申领中添加 -->
      <el-button
        class="add-sparepart-btn"
        type="text"
        size="medium"
        v-if="materiaCardListData.length > 0"
        @click="openMaterialRequisitionDialog()"
      >{{$t('common.form.preview.materialVerifyEliminate.btn1')}}</el-button>
      <!-- end 从物料申领中添加 -->

      <!-- start 个人库添加按钮 -->
      <el-button
        v-if="!isTaskCloudWarehousePerson && !onlyFromMaterial"
        class="add-sparepart-btn"
        type="text"
        size="medium"
        @click="openMaterialRequisitionDialog('personalLibrary')"
      >{{$t('common.form.preview.materialVerifyEliminate.btn2')}}</el-button>
      <!-- end 个人库添加按钮 -->

    </div>
    
    <!-- start 物料列表 -->
    <el-table
      v-table-style
      v-if="tableValue.length > 0"
      header-row-class-name="base-table-header-v3"
      row-class-name="base-table-row-v3"
      :data="tableValue"
      max-height="250"
      border>

      <el-table-column type="index" width="50" :label="$t('common.base.SN')" fixed="left" />
      
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.field}_${index}_${uuid()}`"
        :label="column.displayName"
        :prop="column.fieldName"
        show-overflow-tooltip
        :min-width="column.minWidth || '108px'"
        :fixed="column.fixed"
      >
        <template slot-scope="scope">
          <template v-if="column.fieldName === 'name'">
            {{ scope.row.materialName || scope.row.name}}
          </template>

          <template v-else-if="column.fieldName === 'salePrice'">
            {{ scope.row | fmt_salePrice_currency }}
          </template>

          <!-- start 汇率换算方式 -->
          <template v-else-if="column.fieldName === 'exchangeMethod'">
            <el-select v-if="scope.row.salePriceCurrency !== totalCurrency" 
              v-model="scope.row.exchangeMethod" 
              @change="exchangeMethodChange(scope.row, scope.$index)"
              :placeholder="$t('common.placeholder.select')">
                <el-option
                  v-for="item in exchangeMethodsOption"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                  >
                </el-option>
              </el-select>
              <span v-else>-</span>
          </template>
          <!-- end 汇率换算方式 -->

          <!-- start 汇率 -->
          <template v-else-if="column.fieldName === 'exchangeRate'">
            <div v-if="scope.row.salePriceCurrency !== totalCurrency" >
              <input 
                :class="['sparepart-number-input', {'el-error': !scope.row.exchangeRate}]" 
                type="number" 
                :disabled="scope.row.exchangeMethod !== 2" 
                v-model="scope.row.exchangeRate" 
                :placeholder="$t('common.placeholder.input2')"
                @change="exchangeRateChange(scope.row, scope.$index)"/>
            </div>
            <span v-else>-</span>
          </template>
          <!-- end 汇率 -->

          <!-- start 换算后单价 -->
          <template v-else-if="column.fieldName === 'conversionPrice'">
            <div v-if='scope.row.exchangeRate && (scope.row.salePriceCurrency !== totalCurrency)'>{{(scope.row.exchangeRate * scope.row.salePrice).toFixed(2) }} {{totalCurrency}}</div>
            <span v-else>-</span>
          </template>
          <!-- end 换算后单价 -->

          <template v-else-if="column.fieldName === 'sn'">
            {{ scope.row.materialSn || scope.row.sn}}
          </template>

          <template v-else-if="column.fieldName === 'materialProperty'">
            {{ scope.row.materialProperty || scope.row.property}}
          </template>
          
          <template v-else-if="column.fieldName === 'materialUnit'">
            {{ scope.row.materialUnit || scope.row.unit}}
          </template>

          <template v-else-if="column.fieldName === 'isSnManageDict'">
            {{ scope.row.isSnManageDict || scope.row.snManage}}
          </template>

          <template v-else-if="column.fieldName === 'warehousePositionName'">
            {{ scope.row.positionName || scope.row.warehousePositionName}}
          </template>

          <!-- start 替换物料 -->
          <template v-else-if="column.fieldName === 'replacedMaterial'">
            <template>
              <biz-remote-select
                :placeholder="$t('common.placeholder.select')"
                :value="[scope.row.replacedMaterial]"
                :remote-method="fetchMaterial"
                @input="chooseMaterial($event, scope.row, scope.$index)"
              >
                <div class="search-in-part-item" slot="option" slot-scope="{ option }">
                  <template v-if="option.name && !loading">
                    <p>{{$t('common.form.preview.materialReturn.tableLabel1')}}：<span>{{ option.name }}</span></p>
                    <p>{{$t('common.form.preview.materialReturn.colum1')}}：<span>{{ option.sn }}</span></p>
                    <p>{{$t('common.form.preview.materialReturn.tableLabel4')}}：<span>{{ option.property }}</span></p>
                  </template>
                  <p class="no_empty" v-else>{{ loading ? $t('common.base.loading') : $t('common.base.tip.noData') }}</p>
                </div>
              </biz-remote-select> 
            </template>
          </template>
          <!-- end 替换物料 -->
          <!-- start 替换物料SN -->
          <template v-else-if="column.fieldName === 'replacedMaterialSN' ">
            <!-- TODO 国际化待办 -->
            <el-input 
              v-if="(scope.row.replacedMaterial && scope.row.replacedMaterial.isSnManageDict === '是') || (scope.row.replacedMaterial && scope.row.replacedMaterial.snManage === '是')"
              @blur="replacedMaterialSNChangVal(scope.row)" 
              v-model="scope.row.replacedMaterialSN" 
              :placeholder="$t('common.placeholder.inputSomething', {data1:'SN'})"
            ></el-input>
            <template v-else>
              {{ scope.row[column.fieldName] }}
            </template>
          </template>
          <!-- end 替换物料SN -->

          <!-- start SN -->
          <template v-else-if="column.fieldName === 'SN'">
            <el-select
              :value="scope.row.SN"
              v-if="scope.row.snManage === '是'"
              :placeholder="$t('common.placeholder.select')" 
              @change="selectChangeSn(...arguments,scope.row)"
            >
              <el-option
                v-for="item in scope.row.snList"
                :key="`${item}_${uuid()}`"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <template v-else>
              {{ scope.row[column.fieldName] }}
            </template>
            
          </template>
          <!-- end 查看SN -->


          <!-- start 批次号 -->
          <template v-else-if="column.fieldName === 'batchNumber'">
            <el-select
              :value="scope.row.batchNumber"
              value-key="batchId"
              v-if="scope.row.snManage !== '是' && (scope.row.batchNumManage === 1 || scope.row.batchNumManage === '是')"
              :placeholder="$t('common.placeholder.select')" 
              @change="selectChangeBatchNum(...arguments,scope.row)"
            >
              <el-option
                v-for="item in getMaterialRelationSelectList(scope.row)"
                :key="`${item}_${uuid()}`"
                :label="item.batchNumber"
                :value="item">
              </el-option>
            </el-select>
            <template v-else>
              {{ scope.row[column.fieldName] }}
            </template>
            
          </template>
          <!-- end 查看SN -->

          <!-- start 操作 -->
          <template v-else-if="column.fieldName === 'action'">
            <el-button class="text-danger" type="text" size="mini" @click="deleteItem(scope)">{{$t('common.base.delete')}}</el-button>
          </template>
          <!-- end 操作 -->

          <!-- start 质保状态、是否SN -->
          <template v-else-if="['warrantyStatus', 'snManage', 'property'].includes(column.fieldName)">
            {{ scope.row[column.fieldName] ? $t(`task.${scope.row[column.fieldName]}`) : scope.row[column.fieldName] }}
          </template>
          <!-- end 质保状态 -->

          <!-- start 富文本 -->
          <template v-else-if="column.formType === 'richtext'">
            <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
              <span v-if="scope.row && (scope.row.attribute && scope.row.attribute[column.fieldName]) || scope.row[column.fieldName]">{{$t('common.base.view')}}</span>
            </div>
          </template>
          <!-- end 富文本 -->

          <!-- start 默认显示 -->
          <template v-else>
            {{ $formatFormField(column, scope.row) }}
          </template>
          <!-- end 默认显示 -->
        </template>
      </el-table-column>
    </el-table>
    <!-- end 物料列表 -->

    <!-- start sn弹窗 -->
    <material-sn-dialog 
      ref="materialSnDialog" 
      :data="tableValue"
      @changeSn="changeSn"
    />
    <!-- end sn弹窗 -->


    <!-- start 从物料申领中添加 -->
    <material-list-dialog 
      :field="field"
      ref="materialListDialog" 
      :value="tableValue"
      :task-id="taskId"
      :task="task"
      :templateId="templateId"
      :columns="materialListColumns"
      :ruleOptions="ruleOptions"
      :isShowSettlementRules="isShowSettlementRules"
      :serviceQualityStatus="serviceQualityStatus"
      :show-replaced-material-check="showReplacedMaterialCheck"
      :isShowSettleType="isShowSettleType"
      @input="confirmApply" 
    />
    <!-- end 从物料申领中添加 -->

    <!-- 富文本弹窗 -->
    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform'
/* components */
import MaterialSnDialog from './components/MaterialSnDialog';
import MaterialListDialog from './components/MaterialListDialog';
import MaterialTable from './components/MaterialTable.vue';
/* mixin */
import FormMixin from '@src/component/form/mixin/form';
/* api */
import * as WareHouseApi from '@src/api/WareHouseApi';
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
/* util */
import { getRootWindow } from '@src/util/dom'
import { findComponentUpward } from '@src/util/assist';
import _ from 'lodash';
import i18n from '@src/locales'
import { exchangeMethodsOption } from '@src/util/currency'
import TaskReceiptMixin from '@src/component/form/mixin/taskReceipt';
import { GrayFunctionEnum } from '@model/grayFunction'
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()

export default {
  name: 'form-materialverifyeliminate',
  mixins: [FormMixin, TaskReceiptMixin],
  inject: ['initData', 'fetchRuleList'],
  props: {
    field: {
      type: Object,
      default: () => ({})
    },
    value: {
      type: Array,
      default: () => ([])
    },
    serviceQualityStatus: {
      type: String,
      default: ''
    },
    // 工单结算规则数据
    settlementRulesList: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      isOpenData,
      visible: false,
      // 窗口是否闪烁
      flickerWindow: false,
      warrantyStatusMap: {
        0: i18n.t('common.base.warranty'),
        1: i18n.t('common.base.surrender')
      },
      // 物料申领列表数据
      materiaCardListData: [],
      loading: false,
      exchangeMethodsOption
    }
  },
  computed: {
    batchSelectGray () {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.[GrayFunctionEnum.BATCH_PERIOD] ?? true // 批次号灰度
    },
    /* 附加组件 */
    cardInfo() {
      return this.initData?.cardInfo || [];
    },
    // 仅可从物料申领中添加物料
    onlyFromMaterial() {
      return this.field?.setting?.onlyFromMaterial || false
    },

    ruleOptions() {
      const { materialVerifyEliminate } = this.settlementRulesList || {};

      return (materialVerifyEliminate || []).map(item => {
        return {
          ...item,
          attribute: item?.attribute ? JSON.parse(item?.attribute) : {}
        }
      }).filter(item => {
        let qualityStatus = this.$t('common.base.surrender')
        if (item.attribute.qualityStatus == 'IN' || item.attribute.qualityStatusName == '保内') {
          qualityStatus = this.$t('common.base.warranty')
        }
        return this.serviceQualityStatus ? (qualityStatus === this.serviceQualityStatus) : item
      })
    },
    
    handlerMaterialReturnOutSide(){
      let { handlerMaterialReturnOutSide } = findComponentUpward(this, 'form-builder');
      return handlerMaterialReturnOutSide
    },    
    tableValue(){
      return this.value || []
    },
    /** 
    * @description 质保状态
    */
    warrantyStatus() {
      let { warrantyStatus } = this.initData?.materialInfo || {}
      warrantyStatus = warrantyStatus === 'IN' ? 0 : 1
      return this.warrantyStatusMap[warrantyStatus] || ''
    },
    /**
    * @description 是否显示质保字段
    */
    showWarrantyStatus() {
      let { showWarrantyStatus } = this.initData?.materialInfo || {}
      return showWarrantyStatus
    },

    //  是否需要填写被替换物料
    showReplacedMaterialCheck() {
      let { replacedMaterialCheck } = this.initData?.materialInfo || {}
      return replacedMaterialCheck || false
    },

    /**
    * @description 工单id（在mixin文件中使用）
    */
    taskId() {
      return this.initData.task.id
    },

    /**
    * @description 工单信息
    */
    task() {
      return this.initData.task
    },
    /**
     * 工单类型ID
     */
    templateId() {
      return this.initData?.task?.templateId || '';
    },
    // 关联物料字段
    relationMaterialFields() {
      let newFields = (this.field?.setting?.materialFields || []).map(item => {
        return {
          ...item,
          displayName: item?.displayName || item?.label,
          fieldName: item?.field || item?.fieldName
        }
      })
      return newFields;
    },
    /**
    * @description 回执物料列表项
    */
    columns() {
      // TODO 涉及displayName的判断 业务线自己处理
      let columns = [
        ...this.relationMaterialFields,
        {
          displayName: this.$t('common.form.preview.materialReturn.tableLabel3'),
          fieldName: 'SN'
        }, 
        {
          displayName: this.$t('common.currency.exchangeMethod'),
          fieldName: 'exchangeMethod',
        },
        {
          displayName: this.$t('common.currency.exchangeRate'),
          fieldName: 'exchangeRate',
        },
        {
          displayName: this.$t('common.currency.conversionPrice'),
          fieldName: 'conversionPrice',
        },
        {
          displayName: this.$t('common.form.preview.materialReturn.tableLabel14'),
          fieldName: 'batchNumber'
        }, 
        {
          displayName: this.$t('common.form.preview.materialReturn.tableLabel7'),
          fieldName: 'warrantyStatus',
          fixed: 'right',
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum9'),
          fieldName: 'warehouseName',
          fixed: 'right',
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum12'),
          fieldName: 'warehousePositionName',
        },
        {
          displayName: this.$t('common.form.preview.materialVerifyEliminate.settleType'),
          fieldName: 'settleType',
          minWidth: '110px'
        },
        {
          displayName: this.$t('common.form.preview.materialVerifyEliminate.applyNum'),
          fieldName: 'number',
          minWidth: '120px'
        },
        {
          displayName: this.$t('common.form.preview.sparepart.colum22'),
          fieldName: 'replacedMaterial',
          minWidth: '150px',
          fixed: 'right',
        }, 
        {
          displayName: this.$t('common.form.preview.sparepart.colum25'),
          fieldName: 'replacedMaterialSN',
          fixed: 'right',
        }, 
        {
          displayName: this.$t('common.zhongqi.title1'),
          fieldName: 'settlementRules',
          fixed: 'right',
        },
        {
          displayName: this.$t('common.base.table.col.operator'),
          fieldName: 'action',
          minWidth: '70px',
          fixed: 'right',
        }
      ]
      if(!this.showWarrantyStatus) {
        columns = columns.filter(item => item.fieldName !== 'warrantyStatus')
      }

      if (!this.isShowSettlementRules) {
        columns = columns.filter(item => item.fieldName !== 'settlementRules')
      }
      
      if(!this.batchSelectGray) {
        columns = columns.filter(item => item.fieldName !== 'batchNumber')
      }

      // TODO国际化灰度未开启
      if(!internationalGray) {
        let arr = ['exchangeMethod', 'exchangeRate', 'conversionPrice']
        columns = columns.filter(item => !(arr.includes(item.fieldName)))
      }
      if(!this.showReplacedMaterialCheck){
        columns = columns
          .filter(item => item.fieldName !== 'replacedMaterial')
          .filter(item => item.fieldName !== 'replacedMaterialSN')
      }

      // 完成回执-物料核销 是否隐藏终端销售价
      if(!this.serviceProviderShowPrice) {
        columns = columns.filter(field => field.fieldName !== 'salePrice' && field.fieldName !== 'conversionPrice')
      }

      // 未开启 配件结算方式
      if (!this.isShowSettleType) {
        columns = columns.filter(item => item.fieldName !== 'settleType')
      }

      return columns;
    },
    /**
    * @description 已完成出库物料清单列表项
    */
    materialListColumns() {
      let columns = this.columns.slice()
      columns.push({
        displayName: this.$t('common.form.preview.sparepart.colum13'),
        fieldName: 'availableNum'
      })
      columns = columns.filter(item => item.fieldName !== 'action')
      return columns
    },

    // 是否开启个人库灰度
    isTaskCloudWarehousePerson() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskCloudWarehousePerson || false
    },
    // 结算规则灰度
    isSettlementRule() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.settlementRule || false
    }, 
    // 是否显示结算规则
    isShowSettlementRules() {
      return !!this.ruleOptions.length && this.isSettlementRule
    },
    // 是否显示配件结算
    isShowSettleType() {
      // 是否开启慈星物料核销灰度
      const RootWindow = getRootWindow(window)
      const isCiXingMaterialGray = RootWindow.grayAuth?.CIXING_MATERIAL_SETTLE
      
      return isCiXingMaterialGray && this.field?.setting?.isShowSettleType
    },
  },
  watch: {
    visible(n) {
      this.chooseDefaultProduct()
    }
  },
  created(){
    // 存在被替换物，才进行下一步
    if(this.showReplacedMaterialCheck){
      // 拿到被替换物料的id，因为id有重复的，所以去下重
      const materialIds = this.getMaterialIds(this.value)
      this.fetchMaterial({ materialIds })
    }
    this.updateMaterialTableData()
    this.getInventoryByCardId()
  },
  methods: {
    getMaterialRelationSelectList(row) {
      const materialRelationList = row.materialRelationList || (row?.batchNumber ? [{ batchNumber: row.batchNumber, num: row.number }] : [])
      return materialRelationList.filter(item=> item.num >= row.number)
    },
    /** 
    * @description 查询物料申领列表数据
    */
    async getInventoryByCardId() {
      const materiaCard = this.cardInfo.filter(item => item.cardName === "物料申领")
      try {
        const params = {
          cardId: materiaCard[0].cardId,
          taskId: this.task.id
        }
        
        let res = await TaskApi.getInventoryByCardId(params);
        if (!res.success || !res.result) return;
        this.materiaCardListData = res.result || []
      } catch(err) {
        console.error('sparepart getInventoryByCardId err', err)
      }
    },
    // getWarrantyStatus(val) {
    //   console.log(val, '质保的状态')
    //   return val || this.serviceQualityStatus
    // },
    // 选择物料
    chooseMaterial(value, row, index) {
      let item = value?.[0] || {}
      let selectedMaterial = {
        id: item.id || item.materialId,
        materialId: item.id || item.materialId,
        image: item.image,
        images: item.images,
        materialName :item.materialName || item.name,
        name :item.materialName || item.name,
        isReplaced:  item.isReplaced,
        isSnManage:  item.isSnManage,
        value: item.value || item.id,
        label: item.label || item.name,
        num:  item.num,
        property :item.property || item.materialProperty,
        salePrice:  item.salePrice || 0,
        serialNumberList:  item.serialNumberList,
        sn: item.sn || item.materialSn,
        materialSn: item.sn || item.materialSn,
        unit :item.unit || item.materialUnit,
        snManage :item.snManage || item.isSnManageDict,
      }
      if(!selectedMaterial.id) return;
      // // 判断当前选择的物料是否已经存在, 排除本身
      // let idx = this.tableValue.findIndex(item => item?.replacedMaterial?.id == selectedMaterial.id);
      // if(idx > -1 && idx != index) return this.$platform.toast('该记录已存在！', 'warning');
      if(row && row.replacedMaterialSN){
        row.replacedMaterialSN = ''
      }
      let newData = this.tableValue.slice();
      newData[index].replacedMaterial = selectedMaterial
      this.handlerMaterialReturnOutSide(_.cloneDeep(newData[index]), 'edit')
      this.updateMaterialTableData()
    },
    /**
     * @description 搜索物料
    */
    async fetchMaterial(params) {
      try {
        this.loading = true;
        const { keyword = '', pageNum = 1, pageSize = 10 } = params
        // 查库存
        let fn = 'getMaterialList'
        let isParams = {
          keyword,
          pageNum,
          pageSize,
          positionId: this.positionId,
          warehouseId: this.warehouseId
        }
        if(params.materialIds){
          isParams.materialIds = params.materialIds
        }

        let res = await WareHouseApi[fn](isParams);
        this.loading = false;
        if (!res.success) return;
        res.data.list = res.data.list.map(item => {
          return {
            label: item.name,
            value: item.id,
            ...item,
          }
        });
        return res.data;
      } catch (error) {
        this.loading = false;
        console.warn('fetchMaterial -> error', error);
      } 
    },

    openSnDialog(type, row, index) {
      let isMaterialApply = false
      if(row.isOutWarehouse) {
        isMaterialApply = true
      }
      this.$refs.materialSnDialog.open(type, row, index, isMaterialApply)
    },

    // 被替换物料SN改变
    replacedMaterialSNChangVal(row){
      // 当前选择的被替换物料的ID
      const replacedId = row.replacedMaterial?.materialId || row.replacedMaterial?.id
      // 当前输入的被替换物料的SN
      const replacedSN = row.replacedMaterialSN
      // 当前输入的被替换物料相同SN的数据
      const sameData = this.checkSelectMaterialSn(replacedSN, replacedId)
      // 本身已经是一条数据了，所以只要大于 1 就代表当前输入的被替换物料的SN已经存在。
      if(sameData.length > 1){
        row.replacedMaterialSN = ''
        return this.$message.warning('存在相同的SN, 请重新输入!')
      }
      this.handlerMaterialReturnOutSide(_.cloneDeep(row))
      this.updateMaterialTableData()
    },
    // sn改变事件
    selectChangeSn(newVal,row){
      // 和当前SN相同SN的数据
      const sameData = this.checkSelectMaterialSn(newVal, row.materialId)
      if(sameData.length > 0) return this.$message.warning('SN不可重复,请检查后重试')
      this.handlerMaterialReturnOutSide(_.cloneDeep(row), 'snChange')
      row.SN = newVal
      this.updateMaterialTableData()
    },
    // 批次号改变事件
    selectChangeBatchNum(newVal, row){
      // 和当前SN相同SN的数据
      // const sameData = this.checkSelectMaterialSn(newVal.batchId, row.materialId)
      // if(sameData.length > 0) return this.$message.warning('批次号不可重复,请检查后重试')
      const hasSameBatchNumber = this.tableValue.some(item=> item.batchNumber === newVal.batchNumber)
      if(hasSameBatchNumber) return this.$message.warning(this.$t('common.form.preview.materialReturn.materialReturnInformationDialog.batchInfo'))
      // 暂时不用 --后续可能需要 TODO
      // this.handlerMaterialReturnOutSide(_.cloneDeep(row), 'snChange')
      // row.materialRelation = newVal
      row.batchNumber = newVal.batchNumber
      row.batchId = newVal.batchId
      this.updateMaterialTableData()
    },
    // 检验相同物料选择的SN和填写的SN是否相同
    checkSelectMaterialSn(sn, id){
      // 当前选择的物料的ID
      const replacedId = id
      // 当前物料的SN
      const replacedSN = sn
      // 核销列表中已选择的SN
      const data = this.tableValue.filter(item => item.materialId === replacedId).map(item => item.SN)
      // 被替换物料中已经填写的SN
      const replaceData = this.tableValue
        .filter(item => (item.replacedMaterial?.materialId || item.replacedMaterial?.id) === replacedId)
        .filter(item => Boolean(item.replacedMaterialSN))
        .map(item => item.replacedMaterialSN)
      // 和当前SN相同SN的数据
      const sameData = [...data, ...replaceData].filter(item => item === replacedSN)
      return sameData
    },

    updateMaterialTableData() {
      window.localStorage.setItem('materialTableData', JSON.stringify(this.tableValue))
    },
    changeSn(data) {
      this.$emit('update', { field: this.field, newValue: data });
    },
    /**
    * @description 初始化备件默认值
    */
    _initData() {
      let _initData = {
        id: '',
        name: '',
        materialSn: '',
        type: '',
        standard: '',
        salePrice: '',
        costPrice: '',
        number: '',
        unit: '',
        availableNum: '',
        repertoryCount: '',
        description: '',
        repertoryName: '',
        repertoryStaffId: '',
        repertoryId: '',
        sparePartId: ''
      }

      return _initData
    },
    /**
    * @description 弹窗关闭重置数据
    */
    reset() {
      // 清空校验结果
      this.$refs.form.$children.map(child => {
        if (child.$el.className == 'form-item err') {
          child.$el.dispatchEvent(new CustomEvent('form.clear.validate', {bubbles: false}));
        }
      })
    },
    async confirmApply({ data, refsName }) {
      let exchangeRateObj = {}
      if(internationalGray) {
        exchangeRateObj = await this.getCurrenyKeyArr(data, this.totalCurrency)
      }

      // 查找已添加的物料中是否存在该物料
      data.forEach((item, index) => {
        let salePriceCurrency = item?.salePriceCurrency || 'CNY'

        if(this.showReplacedMaterialCheck || item.snManage === '是'){
          const copyData = _.cloneDeep(item.snList)
          // oldSnList 代表列表中相同物料已经使用的SN
          let oldSnList = this.tableValue
            .filter(val => val.materialId === item.materialId && (Boolean(val.SN)))
            .map(val => val.SN)

          // 根据存在的snList过滤出不存在的列表
          const materialRelationListItem = (item?.materialRelationList || []).filter(item => oldSnList.indexOf(item.sn) === -1)[0]
          item.SN = materialRelationListItem?.sn || ''
          // item.materialRelation = materialRelationListItem
          item.batchId = materialRelationListItem?.batchId || ''
          item.batchNumber = materialRelationListItem?.batchNumber || ''
        
          this.tableValue.push(item)


          if(internationalGray) {
            this.$set(item, 'exchangeMethod', 1)
            this.$set(item, 'exchangeRate', exchangeRateObj[salePriceCurrency])
          }
        }else{
          if(item.batchNumManage === 1 || item.batchNumManage === '是') {
            const oldBatchNameList = this.tableValue
              .filter(val => val.materialId === item.materialId && (Boolean(val.batchId)))
              .map(val => val.batchId)

            // 根据存在的snList过滤出不存在的列表
            const materialRelationItem = (item?.materialRelationList || []).filter(item => oldBatchNameList.indexOf(item.batchId) === -1)?.[0]
            item.batchNumber = materialRelationItem?.batchNumber || ''
            item.batchId = materialRelationItem?.batchId || ''
            this.tableValue.push(item)


            if(internationalGray) {
              this.$set(item, 'exchangeMethod', 1)
              this.$set(item, 'exchangeRate', exchangeRateObj[salePriceCurrency])
            }
            return
          }

          // 不是SN的则相同物料，相同仓库和相同仓位算是同一种物料
          let idx = this.tableValue.findIndex(val => {
            let materialId = val.materialId ?? val.primaryId
            let warehousePositionId = val.warehousePositionId ?? val.positionId
            return Number(materialId) === item.materialId && val.warehouseId === item.warehouseId && Number(warehousePositionId) === item.warehousePositionId
          })

          if(idx > -1) {
            const newItem = {
              ...this.tableValue[idx],
              ...item,
              number: item.number + this.tableValue[idx].number,
            }
            this.$set(this.tableValue, idx, newItem)
            
          }else{
            if(internationalGray) {
              this.$set(item, 'exchangeMethod', 1)
              this.$set(item, 'exchangeRate', exchangeRateObj[salePriceCurrency])
            }
            this.tableValue.push(item)
          }
        }
      })
      window.localStorage.setItem('materialTableData', JSON.stringify(this.tableValue))
      // 修改了传值 对象改为数组
      this.$emit('update', { field: this.field, newValue: this.tableValue });
      
      this.$refs[refsName].close()
      // 存在被替换物，才进行下一步
      if(this.showReplacedMaterialCheck){
        // 拿到被替换物料的id，因为id有重复的，所以去下重
        const materialIds = this.getMaterialIds(this.tableValue)
        this.fetchMaterial({ materialIds })
      }
    },
    // 获取被替换物的所以物料id集合
    getMaterialIds (data){
      let materialIds = []
      data.forEach(item => {
        let materialId = item?.replacedMaterial?.id ?? item?.replacedMaterial?.materialId
        if(materialId){
          materialIds.push(materialId)
        }
      })
      materialIds = Array.from(new Set(materialIds))
      return materialIds
    },
    deleteItem(scope){
      // 当前删除的数据是表格的第几行数据的下标，从零开始。
      const index = scope.$index 
      this.handlerMaterialReturnOutSide(_.cloneDeep(this.tableValue[index]), 'delete')
      this.tableValue.splice(index, 1)
      window.localStorage.setItem('materialTableData', JSON.stringify(this.tableValue))
      this.$emit('update', { field: this.field, newValue: this.tableValue });
    },
    /**
    * @description 打开物料弹窗
    */
    openAddMaterialDialog(type) {
      let typeMap = {
        title: this.$t('common.form.preview.materialVerifyEliminate.btn2'),
        type: 'personalLibrary'
      }
      // 仓库
      if(type === 'warehouse') {
        typeMap.title = this.$t('common.form.preview.materialVerifyEliminate.btn3')
        typeMap.type = 'warehouse'
      }

      this.$refs.materialApplyDialog.open(typeMap)
    },
    /**
    * @description 物料申领中添加弹窗
    */
    openMaterialRequisitionDialog(type) {
      this.$refs.materialListDialog.open(type)
      this.fetchRuleList()
    },
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.[column.fieldName] || row?.attribute?.[column.fieldName] || ''
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId, false, true);
    }
  },
  components: {
    [MaterialSnDialog.name]: MaterialSnDialog,
    [MaterialListDialog.name]: MaterialListDialog,
    [MaterialTable.name]: MaterialTable
  }
}
</script>

<style lang="scss" scope>
.select-box{
  .el-select-dropdown__item{
    height:80px;
    line-height:20px;
  }
}

.form-sparepart-modal {
  z-index: 990 !important; // 选择地址被遮盖降低层级
}
.form-item.err :not(.is-success){
  .form-item :not(.err) {
    input, textarea, .base-select-main-content {
      border-color: #e0e1e2 !important;
    }
  }

  .form-item.err {
    input, .base-select-main-content {
      border-color: #f56c6c !important;
    }
  }
}

.form-sparepart{
  text-align: left;

  .btn-group {
    padding: 0 !important;

    .el-button {
      min-width: auto !important;
      padding: 8px 0 0 0;
    }
  }

  .el-table {
    margin: 10px 0;

    .sparepart-number-input {
      width: 99%;
    }
    .el-error {
      border: 1px solid #f56c6c
    } 

    .el-icon-delete {
      font-size: 16px;
      color: $color-danger;
      font-weight: 700;
    }
  }
}

.sparepart-template-option {
  * {
    margin: 0;
  }
  padding: 10px 0;
  h3 {
    font-size: 14px;
    font-weight: 500;
    line-height: 24px;
  }

  p {
    display: flex;
    justify-content: space-between;
    line-height: 24px;

    & > span {
      width: 25%;
      display: flex;
      justify-content: flex-start;
      font-size: 12px;
      color: #666666;
      padding-right: 10px;

      & > label {
        flex-shrink: 0;
        padding: 0;
        width: 40px !important;
      }
      & > span {
        flex-grow: 1;
        @include text-ellipsis();
      }
    }
  }
  .sparepart-addition-info {
    & > span {
      width: 50%;
      .addition-product-type {
        width: auto !important;
      }
    }
  }
}
.free-sparepart-fee {
  .iconfont {
    color: #FAAD14;
    margin-right: 8px;
  }
}
.goget-box{
  position: relative;
}
.goget{
  position: absolute;
    right: 35px;
    top: 0;
    line-height: 32px;
    cursor: pointer;
    color: $color-primary-light-6;
}
</style>
<style lang="scss" scoped>
.update-sparepart-title {
  margin-left: 20px;
  color: $color-primary-light-6;
}
.update-sparepart-mess {
  margin: 8px 0px 18px 8px;
  color: $color-primary-light-6;
}
</style>
